package com.supor.aiot.food.ui.food;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alipay.mobile.common.utils.StringUtils;
import com.android.baseconfig.base.BaseActivity;
import com.android.baseconfig.base.BasePresenter;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.utils.DialogUtils;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.android.baseconfig.common.views.ClearEditText;
import com.mpaas.nebula.adapter.api.MPTinyHelper;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.ui.scan.ScanHelper;
import com.supor.aiot.food.R;
import com.supor.aiot.food.adapter.FlowAdapter;
import com.supor.aiot.food.adapter.RecipeHotAdapter;
import com.supor.aiot.food.adapter.RecipeTagsAdapter;
import com.supor.aiot.food.adapter.SearchRecommondAdapter;
import com.supor.aiot.food.api.SearchFoodImpl;
import com.supor.aiot.food.bean.RecipeHotBean;
import com.supor.aiot.food.bean.SearchRecommandBean;
import com.supor.aiot.food.ormlite.Cache;
import com.supor.aiot.food.utils.DoubleClickUtils;
import com.supor.aiot.food.utils.FlowLayoutManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@Route(path = PathUrl.PATH_INTO_SEARCH)
public class IntoSearchActivity extends BaseActivity implements View.OnClickListener, TextView.OnEditorActionListener, TextWatcher {

    private static final String CLASSIFY_POSITION = "CLASSIFY_POSITION";
    ImageView ivHistoryClear;
    TextView tvSearchCancle;
    ClearEditText edtSearch;
    RecyclerView rvSearchHistory;
    RecyclerView rvSearchMore;
    RecyclerView rvSearchNew;
    ImageView ivScane;
    RelativeLayout rlResultTitle;

    //输入完成标志
    private static final int MIN_AMOUT_EDIT_OK = 1000;
    //输入标志
    private static final int MIN_AMOUT_INPUT = 1;
    private Long lastSearchTime;

    private String historyInput;
    private FlowAdapter flowAdapter;
    private SearchRecommondAdapter recomandAdapter;
    private SearchRecommondAdapter nowHotAdapter;
    private List<String> mList;
    private List<Cache> cacheList = new ArrayList<>();
    private List<RecipeHotBean> searchRecommandBeans = new ArrayList<>();
    private List<RecipeHotBean> searchNewBeans = new ArrayList<>();
    private FlowLayoutManager flowLayoutManager;
    private static final String SEARCH_KEYWORD="SEARCH_KEYWORD";
    private static final String SEARCH_DEFAULT = "SEARCH_DEFAULT";
    private static final String RECOMOND_WORD = "RECOMOND_WORD";
    private int code = 1000;
    private boolean ShowState;
    private AppBasicDialog basicDialog;
    private String recomondWord;
    @Override
    protected int resourceId() {
        return R.layout.activity_search;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(resourceId());
        initView();
        initClassifyData();
        initRecycleView();
        initNewRecipe();
        initHotRecipe();
        initListener();
    }

    private void initListener() {
        tvSearchCancle.setOnClickListener(this);
        edtSearch.setOnEditorActionListener(this);
        ivHistoryClear.setOnClickListener(this);
        edtSearch.addTextChangedListener(this);
        flowAdapter.setOnFlowListener(new FlowAdapter.OnFlowClickListener() {
            @Override
            public void OnItemClick(int position) {
                initSearch(cacheList.get(position).getCache());
            }

            @Override
            public void OnItemLongClick(Cache position) {
                /*cacheList.remove(position);
                String export = listToString(cacheList);
                BaseSharedPreferences.setString(IntoSearchActivity.this,Constants.Key.SEARCH_HISTORY,export);
                flowAdapter.setShowMore(ShowState,cacheList);*/
            }

            @Override
            public void OnShowHideClick(boolean state) {
                ShowState=state;
                flowAdapter.setShowMore(ShowState,cacheList);
            }
        });
    }

    //点击软键盘确定
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        int id = v.getId();
        if(id == R.id.edt_common_search){
            if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                if(lastSearchTime != null){
                    long temp = System.currentTimeMillis() - lastSearchTime;
                    if(temp < 1000){
                        return true;
                    }
                }
                lastSearchTime = System.currentTimeMillis();

                String keywords = edtSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(keywords)){
                    compireWords(keywords);
                }else {
                    if (!TextUtils.isEmpty(recomondWord)){
                        compireWords(recomondWord);
                    }
                }
                return true;
            }
        }
        return false;
    }

    private void compireWords(String keywords){
        initSearch(keywords);
        //insert data
        boolean contains = false;
        for (int i=0;i<cacheList.size();i++){
            if (keywords.equals(cacheList.get(i).getCache())){
                contains = true;
            }
        }
        if (!contains){
            Cache cache = new Cache(keywords);
            cacheList.add(0,cache);
            List<String> temp = new ArrayList<>();
            for (int i=0;i<cacheList.size();i++){
                temp.add(cacheList.get(i).getCache());
            }
            String export = listToString(temp);
            BaseSharedPreferences.setString(IntoSearchActivity.this,Constants.Key.SEARCH_HISTORY,export);
            rlResultTitle.setVisibility(View.VISIBLE);
            rvSearchHistory.setVisibility(View.VISIBLE);
            flowAdapter.setShowMore(ShowState,cacheList);
        }
    }

    /**
     * 美味上新
     */
    @SuppressLint("AutoDispose")
    private void initNewRecipe(){
        SearchFoodImpl.getInstance().getNewestRecipe(1,10).subscribe(result -> {
            if (result.isSuccess()) {
                searchNewBeans.clear();
                for (int i = 0;i<6;i++){
                    searchNewBeans.add(result.data.rows.get(i));
                }
                nowHotAdapter.notifyDataSetChanged();
            } else {
                Log.e(TAG, "rsult error");
            }
        }, throwable -> {
            Log.e(TAG, "查询失败: " + throwable.getMessage());

        });
    }

    /**
     * 大家都在做
     */
    @SuppressLint("AutoDispose")
    private void initHotRecipe(){
        SearchFoodImpl.getInstance().getPopularRecipe(1,10).subscribe(result -> {
            if (result.isSuccess()) {
                searchRecommandBeans.clear();
                for (int i = 0;i<6;i++){
                    searchRecommandBeans.add(result.data.rows.get(i));
                }
                recomandAdapter.notifyDataSetChanged();
            } else {
                Log.e(TAG, "rsult error");
            }
        }, throwable -> {
            Log.e(TAG, "查询失败: " + throwable.getMessage());

        });
    }

    /**
     * 搜索详情页
     * @param keyword
     */
    public void initSearch(String keyword){
        edtSearch.setText(keyword);
        Intent intent = new Intent(IntoSearchActivity.this,SearchResultActivity.class);
        intent.putExtra(SEARCH_KEYWORD,keyword);
        intent.putExtra(SEARCH_DEFAULT,recomondWord);
        startActivityForResult(intent,code);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        initClassifyData();
    }

    @Override
    protected void onPause() {
        setSoftInputMode(false);
        hideKeyboard(IntoSearchActivity.this,edtSearch);
        super.onPause();
    }

    public String listToString(List list) {
        StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                if (i == list.size() - 1) {
                    sb.append(list.get(i));
            } else {
                    sb.append(list.get(i));
                    sb.append(",");
            }
        }
            return sb.toString();
    }

    private List<String> stringToList(String strs){
        if (!StringUtils.isEmpty(strs)){
            String str[] = strs.split(",");
            return Arrays.asList(str);
        }else {
            return new ArrayList<>();
        }
    }

    @Override
    protected void initView() {
        super.initView();
        ivHistoryClear = findViewById(R.id.iv_history_clean);
        tvSearchCancle = findViewById(R.id.tv_search_cancle);
        rvSearchHistory = findViewById(R.id.rv_search_history);
        edtSearch = findViewById(R.id.edt_common_search);
        rvSearchMore = findViewById(R.id.rv_search_more);
        rvSearchNew = findViewById(R.id.rv_search_new);
        ivScane = findViewById(R.id.iv_scan);
        rlResultTitle = findViewById(R.id.rl_result_title);
    }

    private void setSoftInputMode(boolean visible) {
        if (visible) {
            if (getWindow() != null) {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
            }
        } else {
            if (getWindow() != null) {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            }
        }
    }


    public static void hideKeyboard(Activity activity, View view) {
        if (activity != null) {
            if (view != null) {
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            } else {
                hideKeyboard(activity);
            }
        }
    }

    public static void hideKeyboard(Activity activity) {
        if (activity != null) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null && activity.getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
                if (null != activity.getCurrentFocus()) {
                    activity.getCurrentFocus().clearFocus();
                }
            }
        }
    }

    private void openKeyboard(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() { //弹出软键盘的代码
                InputMethodManager imm = (InputMethodManager)IntoSearchActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(edtSearch, InputMethodManager.RESULT_SHOWN);
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
            }
        }, 500);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initRecycleView() {
        if (cacheList!=null){
            flowAdapter=new FlowAdapter(cacheList,IntoSearchActivity.this);
            flowLayoutManager = new FlowLayoutManager();
            rvSearchHistory.setAdapter(flowAdapter);
            rvSearchHistory.setLayoutManager(flowLayoutManager);
        }
        recomandAdapter=new SearchRecommondAdapter(searchRecommandBeans, IntoSearchActivity.this, position -> {
            AppAgent.startRecipePage(searchRecommandBeans.get(position).getRecipeId(), searchRecommandBeans.get(position).getModelId());
//            IntoSearchActivity.this.finish();
        });
        recomandAdapter.setShowDate(false);
        nowHotAdapter=new SearchRecommondAdapter(searchNewBeans,IntoSearchActivity.this,position->{
            AppAgent.startRecipePage(searchNewBeans.get(position).getRecipeId(), searchNewBeans.get(position).getModelId());
//            IntoSearchActivity.this.finish();
        });
        nowHotAdapter.setShowDate(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(IntoSearchActivity.this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        rvSearchNew.setLayoutManager(linearLayoutManager);
        rvSearchNew.setAdapter(nowHotAdapter);

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(IntoSearchActivity.this);
        linearLayoutManager1.setOrientation(RecyclerView.VERTICAL);
        rvSearchMore.setLayoutManager(linearLayoutManager1);
        rvSearchMore.setAdapter(recomandAdapter);
    }


    @SuppressLint("AutoDispose")
    private void initNewRecomond() {
        recomondWord = getResources().getString(R.string.default_recomond);
        SearchFoodImpl.getInstance().getNewRecomond().subscribe(result -> {
            if (result.isSuccess()) {
                if (!TextUtils.isEmpty(result.data.rows.get(0).getRecipeName())) {
                    recomondWord = result.data.rows.get(0).getRecipeName();
                    edtSearch.setHint(recomondWord);
                }
            } else {
                Logc.e(result.message);
                edtSearch.setHint(recomondWord);
            }
        }, throwable -> {
            Logc.e(throwable.getMessage());
            edtSearch.setHint(recomondWord);
        });
    }

    private void initClassifyData() {
        historyInput = BaseSharedPreferences.getString(IntoSearchActivity.this,Constants.Key.SEARCH_HISTORY);
        recomondWord = getIntent().getStringExtra(RECOMOND_WORD);
        if (!TextUtils.isEmpty(recomondWord)){
            edtSearch.setHint(recomondWord);
        }else {
            initNewRecomond();
        }
        mList = stringToList(historyInput);
        cacheList.clear();
        if (mList!=null&&mList.size()>0){
            for (int i=0;i<mList.size();i++){
                Cache cache = new Cache(i,mList.get(i));
                cacheList.add(cache);
            }
        }
        if (cacheList.size()==0){
            rlResultTitle.setVisibility(View.GONE);
            rvSearchHistory.setVisibility(View.GONE);
        }else {
            rlResultTitle.setVisibility(View.VISIBLE);
            rvSearchHistory.setVisibility(View.VISIBLE);
        }
        if (flowAdapter!=null)flowAdapter.setShowMore(ShowState,cacheList);
    }

    @Override
    protected void onResume() {
        super.onResume();
        edtSearch.requestFocus();
        setSoftInputMode(true);
        openKeyboard();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_search_cancle) {
            IntoSearchActivity.this.finish();
        }else if (view.getId() == R.id.iv_history_clean) {
            if (DoubleClickUtils.isFastDoubleClick())return;
            setSoftInputMode(false);
            hideKeyboard(IntoSearchActivity.this,edtSearch);
            basicDialog = DialogUtils.easyTipsDialog(IntoSearchActivity.this, R.string.confirm_delete, (dialogInterface, i) -> {
                cacheList.clear();
                BaseSharedPreferences.setString(IntoSearchActivity.this,Constants.Key.SEARCH_HISTORY,null);
                flowAdapter.setShowMore(ShowState,cacheList);
                rlResultTitle.setVisibility(View.GONE);
                rvSearchHistory.setVisibility(View.GONE);
                basicDialog.dismiss();
            });
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        edtSearch.setSelection(editable.length());
    }

}
